package com.obrock;

import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

/**
 * Created with IntelliJ IDEA.
 * User: Дмитрий Г. Кузнецов
 * Date: 15.10.12
 * Time: 16:33
 * To change this template use File | Settings | File Templates.
 */
public class ViewTransfers extends LinearLayout {
    Account selectedAccount;
    int bgColor;
    Context context;
    Balance[] transfers = null;
    Balance selectedTransfer = null;
    Drawable img = null;

    public ViewTransfers(Account account, Balance selected, Context context) {
        super(context);
        this.context = context;
        this.selectedAccount = account;
        this.selectedTransfer = selected;
        refresh();
    }

    public ViewTransfers(Account account, Balance selected, Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        this.selectedAccount = account;
        this.selectedTransfer = selected;
        refresh();
    }

    /*
    public ViewTransfers(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    */

    public Balance refresh(Balance selected) {
        this.selectedTransfer = selected;
        return refresh();
    }

    public Balance refresh(Account account, Balance selected, int color) {
        this.selectedAccount = account;
        this.selectedTransfer = selected;
        bgColor = color;
        return refresh();
    }

    Balance refresh() {
        inflate(context, R.layout.transfers, this);
        //setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        TableLayout container = null;
        container = (TableLayout) findViewById(R.id.container_transfers);
        container.setColumnShrinkable(1, true);
        container.setColumnStretchable(1, true);
        container.removeAllViews();

        if (selectedAccount == null) return null;

        setBackgroundColor(bgColor);

        selectedAccount.refreshBalance();

        transfers = Main.db.getTransfers(selectedAccount);

        if (selectedTransfer == null && transfers.length > 0) {
            selectedTransfer = transfers[transfers.length - 1];
        }


        double balance = selectedAccount == null ? 0.0 : selectedAccount.amount;
        double balanceDebt = 0.0;
        double balanceCredit = 0.0;

        int id = -1;
        View current = null;

        TableRow xrow = null;

        for (int i = 0; i < transfers.length; ++i) {
            Balance transfer = transfers[i];
            //boolean approved = new Balance(selectedTransfer.parentID).approved(viewPeriod);

            double transferAmount = 0.0;
            String subTitle = "";

            ImageView icon = new ImageView(context);
            icon.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            icon.setAdjustViewBounds(true);
            icon.setMaxHeight(32);
            icon.setMaxWidth(32);
            icon.setPadding(0, 4, 0, 0);

            LinearLayout iconHolder = new LinearLayout(context);
            iconHolder.addView(icon);
            LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            iconHolder.setLayoutParams(param);

            if (transfer.accountFrom != null
                    && selectedAccount != null
                    && transfer.accountFrom.accountID == selectedAccount.accountID) {
                transferAmount = transfer.amount;
                icon.setImageDrawable(getResources().getDrawable(R.drawable.out));
                balance -= transferAmount * (selectedAccount.type == Account.TYPE_DEBT ? -1 : 1);

                if (transfer.type == Balance.TYPE_COMPLEX) {
                    subTitle = "";
                    for (Complex c : transfer.complex) {
                        if (subTitle.length() > 0) subTitle += ", ";
                        if (c.account != null) {
                            subTitle += c.account.name;
                        } else {
                            subTitle += getResources().getString(R.string.transfer_empty);
                        }
                    }
                } else if (transfer.accountTo != null) {
                    subTitle = transfer.accountTo.name;
                } else {
                    subTitle = getResources().getString(R.string.transfer_empty);
                }
            } else {
                if (transfer.type == Balance.TYPE_NORMAL) {
                    transferAmount = transfer.amount;
                } else {
                    transferAmount = 0;
                    for (Complex c : transfer.complex) {
                        if (c.account != null && c.account.accountID == selectedAccount.accountID) {
                            transferAmount += c.amount;
                        }
                    }
                }
                if (transfer.accountFrom != null) {
                    subTitle = transfer.accountFrom.name;
                } else {
                    subTitle = getResources().getString(R.string.transfer_empty);
                }
                icon.setImageDrawable(getResources().getDrawable(R.drawable.in));
                balance += transferAmount * (selectedAccount.type == Account.TYPE_DEBT ? -1 : 1);
            }


            LinearLayout column2 = new LinearLayout(context);
            column2.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            column2.setOrientation(LinearLayout.VERTICAL);

            TextView name = Main.getTextView(context, transfer.name);
            name.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            name.setTextSize(16);


            LinearLayout subrow = new LinearLayout(context);
            subrow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            subrow.setOrientation(LinearLayout.HORIZONTAL);

            TextView date = Main.getTextView(context, Main.datetimeString(transfer.date));
            date.setTextSize(12);
            date.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            date.setTextColor(getResources().getColor(R.color.total_color));

            TextView sub = Main.getTextView(context, subTitle);
            sub.setTextSize(12);
            sub.setPadding(8, 0, 0, 0);

            subrow.addView(date);
            subrow.addView(sub);

            column2.addView(name);
            column2.addView(subrow);

            String anal = "";
            for (Analytics a : transfer.analytics.keySet()) {
                if (transfer.analytics.get(a) != null) {
                    if (anal.length() > 0) anal += ", ";
                    anal += transfer.analytics.get(a).name;
                }
            }

            if (anal.length() > 0) {
                TextView vanal = Main.getTextView(context, anal);
                vanal.setTextSize(12);
                vanal.setTextColor(getResources().getColor(R.color.list_color));
                column2.addView(vanal);
            }

            LinearLayout column3 = new LinearLayout(context);
            column3.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            column3.setOrientation(LinearLayout.VERTICAL);

            TextView amount = Main.getTextView(context, String.format("%.2f", transferAmount));
            amount.setGravity(Gravity.RIGHT);
            amount.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            amount.setTextSize(16);
            column3.addView(amount);

            TextView bal = Main.getTextView(context, String.format("%.2f", balance));
            bal.setTextSize(12);
            bal.setGravity(Gravity.RIGHT);
            column3.addView(bal);


            xrow = Main.addRow(context, bgColor, i, new View[]{
                    iconHolder,
                    column2,
                    column3
            });

            xrow.setTag(Main.tagTransfer);

            //if (viewMode == VIEW_PROGNOSIS) {
            ///recolor(xrow, getResources().getColor(R.color.approved));
            //}

            xrow.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    int id = view.getId();
                    selectedTransfer = transfers[id];
                    Main.setObject(Main.VIEW_TRANSFERS, selectedTransfer);
                    Main.refreshCursor((ViewGroup) view.getParent(), id, bgColor);
                    return false;
                }
            });

            xrow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {

                    ViewGroup v = (ViewGroup) view.getParent();
                    int id = view.getId();

                    selectedTransfer = transfers[view.getId()];
                    Main.doAction(Main.VIEW_TRANSFERS, selectedTransfer);
                    /*
                    if (Main.splitMode == Main.SPLIT_DOUBLE) {
                        if (Main.viewMode == Main.VIEW_TRANSFERS) {
                            details.refresh(selectedTransfer);
                            //Main.context.refreshDetails(getResources().getColor(R.color.pane_color));
                        } else {
                            Main.viewMode = Main.VIEW_TRANSFERS;
                            Main.context.refreshView(Main.VIEW_TRANSFERS, selectedTransfer);
                        }
                    } else {
                        Main.viewMode = Main.VIEW_DETAILS;
                        Main.context.refreshView();
                    }
                    */
                }
            });

            Main.context.registerForContextMenu(xrow);
            container.addView(xrow);

            if (selectedTransfer != null && transfers[i].balanceID == selectedTransfer.balanceID) {
                id = i;
                current = xrow;
            }

        }


        if (id != -1) {
            Main.refreshCursor(container, id, bgColor);
            ((ScrollView) findViewById(R.id.scroll_transfers)).post(
                    new ScrollTo(((ScrollView) findViewById(R.id.scroll_transfers)), current));
        } else if (xrow != null) {
            ((ScrollView) findViewById(R.id.scroll_transfers)).post(
                    new ScrollTo(((ScrollView) findViewById(R.id.scroll_transfers)), xrow));
        }

        switch (selectedAccount.type) {
            case Account.TYPE_NORMAL:
                img = getResources().getDrawable(R.drawable.wallet);
                break;
            case Account.TYPE_DEBT:
                img = getResources().getDrawable(R.drawable.credit);
                break;
            case Account.TYPE_CARD:
                img = getResources().getDrawable(R.drawable.card);
                break;
        }

        //Main.refreshHeader();
        return selectedTransfer;

        /*
Main.context.viewHeader.set(img,
        selectedAccount.name,
        String.format(getResources().getString(R.string.account_balance), selectedAccount.balance));
        */

        /*
        if (Main.viewMode == Main.VIEW_TRANSFERS) {
            TextView accountTitle = (TextView) findViewById(R.id.account_title);
            TextView accountBalance = (TextView) findViewById(R.id.account_amount);
            TextView accountDetails = (TextView) findViewById(R.id.account_debt);
            ImageView accountIcon = (ImageView) findViewById(R.id.icon);

            LinearLayout blockLines = (LinearLayout) findViewById(R.id.block_lines);
            LinearLayout blockColumns = (LinearLayout) findViewById(R.id.block_columns);

            blockLines.setVisibility(View.VISIBLE);
            blockColumns.setVisibility(View.GONE);

            accountTitle.setText(selectedAccount.name);
            accountBalance.setText(getResources().getString(R.string.account_balance, selectedAccount.balance));
            if (selectedAccount.balanceCredit > 0 && selectedAccount.balanceCredit != selectedAccount.balance) {
                accountDetails.setText(getResources().getString(R.string.account_credit, selectedAccount.balanceCredit));
            } else if (selectedAccount.balanceDebt > 0 && selectedAccount.balanceDebt != selectedAccount.balance) {
                accountDetails.setText(getResources().getString(R.string.account_debt, selectedAccount.balanceDebt));
            }

            switch (selectedAccount.type) {
                case Account.TYPE_NORMAL:
                    accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.wallet));
                    break;
                case Account.TYPE_DEBT:
                    accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.credit));
                    break;
                case Account.TYPE_CARD:
                    accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.card));
                    break;
            }

        }
        */
    }


    public Drawable getImage() {
        return img;
    }
}
